<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" class="formFlex" label-width="80px"
             size="small">
      <el-form-item label="" prop="agentId">
        <el-select v-model="queryParams.agentId" class="labelWidth" clearable filterable placeholder="请选择代理商"
                   @change="getAllStation">
          <el-option
            v-for="dict in agentList"
            :key="dict.id"
            :label="dict.agentName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="chargeStationId">
        <el-select v-model="queryParams.chargeStationId" class="labelWidth" clearable filterable
                   placeholder="请选择场站"
                   @change="handleStation">
          <el-option
            v-for="item in stationNewList"
            :key="item.id"
            :label="item.stationName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="deviceId">
        <el-select v-model="queryParams.deviceId" class="labelWidth" clearable filterable placeholder="请选择设备">
          <el-option
            v-for="item in deviceList"
            :key="item.deviceId"
            :label="item.deviceName"
            :value="item.deviceId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="phoneNum">
        <el-input
          v-model="queryParams.phoneNum"
          class="labelWidth"
          clearable
          placeholder="请输入手机号"
          style="width: 130px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="id">
        <el-input
          v-model.number="queryParams.id"
          clearable
          onkeyup="value=value.replace(/[^\d]/g,'')"
          placeholder="请输入订单编号"
          style="width: 140px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="chargeType">
        <el-select v-model="queryParams.chargeType" class="labelWidth" filterable placeholder="请选择支付方式">
          <el-option
            v-for="item in chargeTypeShowList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="status">
        <el-select v-model="queryParams.status" class="labelWidth" filterable placeholder="请选择订单状态">
          <el-option
            v-for="item in statusTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="" prop="timeExport">
        <el-date-picker
          v-model="queryParams.timeExport"
          :default-time="['00:00:00', '23:59:59']"
          :picker-options="pickerOptions"
          align="right"
          clearable
          end-placeholder="充电结束日期"
          range-separator="至"
          start-placeholder="充电开始日期"
          style="width: 240px"
          type="daterange"
          value-format="timestamp"
          @change="timeChange">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="" prop="closeTimeExport">
        <el-date-picker
          v-model="queryParams.closeTimeExport"
          :default-time="['00:00:00', '23:59:59']"
          :picker-options="pickerOptions"
          align="right"
          clearable
          end-placeholder="结算结束日期"
          range-separator="至"
          start-placeholder="结算开始时间"
          style="width: 240px"
          type="daterange"
          value-format="timestamp"
          @change="closeTimeChange">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['business:order:export']"
          :loading="exportStats"
          icon="el-icon-download"
          plain
          size="mini"
          type="warning"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleOrderExport"
          v-hasPermi="['business:workorder:export']"
        >报表导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" :row-class-name="tableRowClassName" highlight-current-row
              @selection-change="handleSelectionChange">
      <el-table-column align="center" label="订单编号" prop="id" width="90"/>
      <el-table-column align="center" label="设备名称" prop="deviceName"/>
      <el-table-column align="center" label="手机号" prop="phoneNum" show-overflow-tooltip/>
      <el-table-column align="center" label="支付方式" prop="chargeTypeShow"/>
      <el-table-column align="center" label="订单来源" prop="sourceType">
        <template slot-scope="scope">
          <el-tag :color="scope.row.sourceType==='VIN'?'#66CCCC':'#FF9900'" effect="dark" type="">
            {{ scope.row.sourceType === 'VIN' ? '即插即充' : '小程序' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="订单状态" prop="statusType">
        <template slot-scope="scope">
          <el-tag :color="statusTypeBg[scope.row.status]" effect="dark" type="">{{ scope.row.statusType }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="充电开始时间" prop="createTime" width="160"/>
      <el-table-column align="center" label="充电结束时间" prop="chargeEndTime" width="160"/>
      <el-table-column align="center" label="充电耗时" prop="chargingTime"/>
      <el-table-column align="center" label="结束原因" prop="endTypeStr"/>
      <el-table-column align="center" label="耗电量" prop="chargeElectricity">
        <template slot-scope="scope">
          {{formatNumber(scope.row.chargeElectricity)}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="结算金额" prop="totalAmountShow" width="80"/>
      <!--      <el-table-column label="开电方式" align="center" prop="beginChargeType">
              <template slot-scope="scope">
                <el-tag :type="scope.row.beginChargeType == '金额模式' ? '' : 'warning'" effect="plain">
                  {{ scope.row.beginChargeType }}
                </el-tag>
              </template>
            </el-table-column>-->

      <!--      <el-table-column label="用户ID" align="center" prop="consumerId" show-overflow-tooltip/>
            <el-table-column label="消费金额" align="center" prop="totalAmountShow" width="80"/>
            <el-table-column label="耗电量(单位:度)" align="center" prop="chargeElectricity" width="120"/>-->


      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status==3"
            slot="reference"
            v-hasPermi="['business:order:edit']"
            icon="el-icon-switch-button"
            size="mini"
            type="text"
            @click="handleEnd(scope.row, charId)"
          >结束订单
          </el-button>

          <el-button
            v-if="scope.row.status==2"
            slot="reference"
            v-hasPermi="['business:order:edit']"
            icon="el-icon-switch-button"
            size="mini"
            type="text"
            @click="handleManualSettlement(scope.row.id)"
          >结算订单
          </el-button>

          <el-button
            v-hasPermi="['business:order:edit']"
            :class="['text-button', { 'active': active===scope.$index }]"
            icon="el-icon-edit"
            size="mini"
            type="text"
            @click="handleDetail(scope.row),active=scope.$index"
          >详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改订单统计对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="开电方式" prop="beginChargeType">
          <el-select v-model="form.beginChargeType" placeholder="请选择开电方式">
            <el-option
              v-for="dict in dict.type.charge_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充电枪" prop="chargePort">
          <el-input v-model="form.chargePort" placeholder="请输入充电枪"/>
        </el-form-item>
        <el-form-item label="用户ID" prop="consumerId">
          <el-input v-model="form.consumerId" placeholder="请输入用户ID"/>
        </el-form-item>
        <el-form-item label="充电设备ID" prop="deviceId">
          <el-input v-model="form.deviceId" placeholder="请输入充电设备ID"/>
        </el-form-item>
        <el-form-item label="计划量" prop="planAmount">
          <el-input v-model="form.planAmount" placeholder="请输入计划量"/>
        </el-form-item>
        <!--        <el-form-item label="版本号" prop="version">
                  <el-input v-model="form.version" placeholder="请输入版本号" />
                </el-form-item>-->
        <!--        <el-form-item label="车辆VIN码" prop="vin">
                  <el-input v-model="form.vin" placeholder="请输入车辆VIN码" />
                </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情 -->
    <el-dialog :visible.sync="openDetail" title="订单详情" width="1800px" @close="closeDetail">
      <el-tabs v-model="activeName" style="height: 500px;" type="border-card" @tab-click="tabClick">
        <el-tab-pane label="订单简报" name="first">
          <el-descriptions v-if="orderDetail" :column="2" border class="margin-top" title="">
            <el-descriptions-item>
              <template slot="label">
                订单编号
              </template>
              {{ orderDetail.id }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                订单状态
              </template>
              {{ orderDetail.statusType }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                开始时间
              </template>
              {{ orderDetail.createTime }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                结束时间
              </template>
              {{ orderDetail.chargeEndTime }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                开电方式
              </template>
              {{ orderDetail.beginChargeType }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                结算状态
              </template>
              {{ orderDetail.statusType }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                结束原因
              </template>
              {{ orderDetail.endTypeStr }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                支付金额
              </template>
              {{ orderDetail.presetAmountShow }}元
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                支付方式
              </template>
              {{ orderDetail.chargeType == 'balance' ? '余额支付' : '微信支付' }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                消费金额
              </template>
              {{ orderDetail.totalAmountShow }}元
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                电费
              </template>
              {{ orderDetail.chargeFeeShow }}元
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                服务费
              </template>
              {{ orderDetail.serviceFeeShow }}元
            </el-descriptions-item>
          </el-descriptions>
          <div class="closeBtn">
            <el-button

              icon="el-icon-switch-button"
              size="mini"
              @click="handleEnd({},charId)"
            >结束订单
            </el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="充电用户">
          <el-descriptions v-if="consumerVo" :column="2" border class="margin-top" title="">
            <el-descriptions-item>
              <template slot="label">
                用户编号
              </template>
              {{ consumerVo.consumerId }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                用户名称
              </template>
              {{ consumerVo.nickName }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                注册手机号
              </template>
              {{ orderDetail.phoneNum }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                注册时间
              </template>
              {{ parseTime(orderDetail.createTime) }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                账户信息
              </template>
              {{ consumerAccount.master }}
              <!--              {{ consumerAccount.master ? '主账户' : '子账户' }}-->
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                账户编号
              </template>
              {{ consumerAccount.accountId }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                账户名称
              </template>
              {{ consumerAccount.accountName }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                现金账户余额
              </template>
              {{ consumerAccount.accountAmount }}元
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                现金账户锁定
              </template>
              {{ consumerAccount.accountAmountLocked }}元
            </el-descriptions-item>

            <el-descriptions-item>
              <template slot="label">
                虚拟账户余额
              </template>
              {{ consumerAccount.virAccountAmount }}元
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                虚拟账户锁定
              </template>
              {{ consumerAccount.virAccountAmountLocked }}元
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="场站设备">
          <div v-if="billingModel" style="display: flex;width: 100%;justify-content: space-between">
            <el-descriptions :column="1" border style="width: 48%" title="充电场站">
              <el-descriptions-item>
                <template slot="label">
                  场站名称
                </template>
                {{ billingModel.stationName }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  场站地址
                </template>
                {{ billingModel.addressInfo }}
              </el-descriptions-item>
            </el-descriptions>
            <el-descriptions :column="1" border style="width: 48%" title="充电桩">
              <el-descriptions-item>
                <template slot="label">
                  设备名称
                </template>
                {{ billingModel.deviceName }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  枪口号
                </template>
                {{ billingModel.chargePort }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
          <div class="el-descriptions__title" style="margin: 20px 0">
            计费模型
          </div>
          <el-table
            v-if="billingModel"
            v-loading="loading"
            :data="billingModel.billingModelDto.billingModelStages"
            max-height="240"
          >

            <el-table-column
              align="center"
              label="顺序号"
              prop="sortNum"/>
            <el-table-column
              :label="billingModel.billingModelDto.billingModel.billingModelStageType == 'T'?'起始时间':'阶段最大功率（单位：W）'"
              align="center"
              prop="duration">
              <template slot-scope="scope">
                {{
                  billingModel.billingModelDto.billingModel.billingModelStageType == 'T' ? ChangeHourMinutestr(scope.row.beginDuration) : scope.row.duration
                }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="服务费"
              prop="serviceFeeShow">

            </el-table-column>
            <el-table-column
              align="center"
              label="电价"
              prop="electricityPriceShow">
              <!--              <template slot-scope="scope">
                              {{ (scope.row.electricityPrice / 100).toFixed(2) }}
                            </template>-->
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="实时数据">
          <!--<div style="height: 60px; line-height: 60px; display: flex; justify-content: center; align-items: center;">
            <el-radio v-model="powerRadio" label="1" style="font-weight: bold">图示</el-radio>
            &lt;!&ndash;<el-radio v-model="powerRadio" label="2" style="font-weight: bold">列表</el-radio>&ndash;&gt;
          </div>-->
          <div v-if="powerRadio==1">
            <el-select v-model="powerValue" placeholder="请选择" style="margin-bottom: 30px;" @change="changePowerType">
              <el-option
                label="功率曲线"
                value="1">
              </el-option>
              <el-option
                label="SOC"
                value="2">
              </el-option>
              <el-option
                label="温度"
                value="3">
              </el-option>
            </el-select>
            <line-chart v-if="openDetail" ref="lineChart" :chart-data="lineChartData" :datetimes="datetimes"
                        :interval="intervalNm" :powerColor="powerColor"
                        :powerMax="powerMax" :powerType="powerType" :powerUnit="powerUnit"/>
          </div>
          <div v-if="powerRadio==2">
            <el-table v-loading="loading" :data="orderList" max-height="250">
              <el-table-column align="center" label="订单编号" prop="id"/>
              <el-table-column align="center" label="开电方式" prop="beginChargeType">
              </el-table-column>
              <el-table-column align="center" label="充电枪" prop="chargePort"/>
              <el-table-column align="center" label="用户ID" prop="consumerId" show-overflow-tooltip/>
              <el-table-column align="center" label="场站名称" prop="stationName" show-overflow-tooltip/>
              <el-table-column align="center" label="充电设备" prop="deviceName" show-overflow-tooltip/>
              <el-table-column align="center" label="手机号" prop="phoneNum" show-overflow-tooltip/>
              <el-table-column align="center" label="订单状态" prop="statusType"/>
            </el-table>
            <pagination
              v-show="total>0"
              :page.sync="queryParams.pageNum"
              :total="total"
              limit.sync="5"
              @pagination="getList"
            />
          </div>
        </el-tab-pane>
      </el-tabs>

    </el-dialog>
  </div>
</template>

<script>
import {
  listOrder,
  getOrder,
  delOrder,
  addOrder,
  updateOrder,
  getChargeTypeList,
  getOrderPower,
  getOrderPowerSoc,
  closeOrder,
  getConsumerAndAccount,
  getChargeAndDevice,
  manualSettlement,
  getOrderPowerTem
} from "@/api/business/order";
import {getAllStation, getAllDeviceByStationId, getAllStationByAgentId} from "@/api/business/station"
import {ChangeHourMinutestr, ChangeStrToMinutes} from '@/utils/common'

import fa from "element-ui/src/locale/lang/fa";
import LineChart from '@/views/dashboard/LineChart1'
import {getAgentAll} from "@/api/platform/agent";

const newVisitis = {
  expectedData: [],
  actualData: [],
  dataV: [],
  dataA: []
}
const statusTypeBg = {
  0: '#66CCCC',
  1: '#CCFF66',
  2: '#FF99CC',
  3: '#99CC33',
  4: '#FF9900',
  5: '#FFCC00',
  6: '#993366',
  7: '#FF0033'
}
const statusTypeList = [
  {
    value: 0,
    label: '创建预订单'
  },
  {
    value: 1,
    label: '加入开电队列'
  },
  {
    value: 2,
    label: '发出开电指令'
  },
  {
    value: 3,
    label: '开电成功'
  },
  {
    value: 4,
    label: '停止充电'
  },
  {
    value: 5,
    label: '结算订单'
  },
  {
    value: 6,
    label: '订单关闭'
  },
  {
    value: 7,
    label: '支付失败'
  },
]
const chargeTypeShowList = [
  {
    value: 'wxPay',
    label: '微信支付'
  },
  {
    value: 'balance',
    label: '微信余额支付'
  },
  {
    value: 'subPay',
    label: '子账户支付'
  },
  {
    value: 'smf',
    label: '扫码富'
  },
  {
    value: 'card',
    label: '充值卡支付'
  },
  {
    value: 'qmf',
    label: '全民付'
  }
]
export default {
  name: "Order",
  computed: {
    fa() {
      return fa
    }
  },
  components: {
    LineChart
  },
  dicts: ['charge_type'],
  data() {
    return {
      statusTypeList,
      chargeTypeShowList,
      agentList: [],
      active: null,
      activeName: 'first',
      ChangeHourMinutestr,
      pickerOptions: {
        disabledDate(time) {
          const date = new Date("2022-12-31 ");
          return time.getTime() < date.getTime();     //禁止选取当天之后的日期（不包括静止当天）
        },
        shortcuts: [{
          text: '最近一个月',
          onClick(picker) {
            const now = new Date();
            const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 59);
            const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        },
          {
            text: '最近两个月',
            onClick(picker) {
              const now = new Date();
              const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 59);
              const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 60);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const now = new Date();
              const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 59);
              const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
      },
      exportStats: false,
      timeExport: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单统计表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        id: null,
        pageNum: 1,
        pageSize: 10,
        agentId: null,
        unitType: null,
        beginChargeType: null,
        chargePort: null,
        consumerId: null,
        deviceId: null,
        planAmount: null,
        status: null,
        version: null,
        vin: null,
        beginTime: null,
        endTime: null,
        timeExport: null,
        closeBeginTime: null,
        closeEndTime: null,
        closeTimeExport: null,
        phoneNum: null,
        chargeStationId: null,
        chargeType: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      chargeTypeList: [],
      openDetail: false,
      powerParams: {
        beginTime: 0,
        endTime: 0,
        deviceId: 0,
        chargeOrderId: 0,
        port: 0
      },
      lineChartData: newVisitis,
      datetimes: [],
      chartDatas: [],
      chartDatas2: [],
      chartDatas3: [],
      powerRadio: '1',
      powerValue: '1',
      powerMax: {},
      powerUnit: [],
      powerColor: '#1890ff',
      orderDetail: {},
      openstatus: '',
      charId: '',
      consumerId: null,
      consumerVo: null,
      consumerAccount: null,
      billingModel: null,
      powerType: '功率',
      stationList: null,
      deviceList: null,
      statusTypeBg: statusTypeBg,
      intervalNm: 0,
      stationNewList: null
    };
  },
  watch: {
    'queryParams.timeExport': {
      deep: true,
      handler(val) {
        if (!val) {
          this.queryParams.beginTime = null
          this.queryParams.endTime = null
        }
      }
    },
    'queryParams.closeTimeExport': {
      deep: true,
      handler(val) {
        if (!val) {
          this.queryParams.closeBeginTime = null
          this.queryParams.closeEndTime = null
        }
      }
    }
  },
  async created() {
    this.one()
    await this.getList();
    await this.getChargeTypeList()
    await this.getAllStationList()
    await this.getAgentAll()
    await this.getAllStation()
  },
  methods: {
    formatNumber(num) {
      return num.toFixed(4)
    },
    //最近一个月
    one() {
      const now = new Date();
      const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 59);
      const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);

      this.queryParams.beginTime = start.getTime()
      this.queryParams.endTime = end.getTime()
      this.queryParams.timeExport = [start, end]
    },
    async getAllStation() {
      if (!this.queryParams.agentId) return
      let res = await getAllStationByAgentId(this.queryParams.agentId)
      this.stationNewList = res.data
    },
    async getAgentAll() {
      let res = await getAgentAll()
      this.agentList = res.rows
    },
    handleManualSettlement(id) {
      this.$confirm('此操作将结算订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          let res = await manualSettlement(id)
          this.$modal.msgSuccess("操作成功");
          this.handleQuery()
        } catch (e) {

        }
        this.$message({
          type: 'success',
          message: '关闭成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });

    },
    tableRowClassName({row, rowIndex}) {
      if (rowIndex % 2 === 1) {
        return 'success-row';
      }
    },
    async getAllDeviceByStationId(id) {
      let res = await getAllDeviceByStationId(id)
      this.deviceList = res.rows
    },
    handleStation(event) {
      this.deviceList = null
      this.queryParams.deviceId = ''
      this.getAllDeviceByStationId(event)
    },
    async getAllStationList() {
      let res = await getAllStation()
      this.stationList = res.data
    },
    tabClick(e) {
      switch (e.index) {
        case '1':
          this.getConsumerAndAccount()
          break;
        case '2':
          this.getChargeAndDevice()
          break;
        case '3':
          this.powerValue = '1'
          this.powerType = '功率'
          this.getPowerData()
          break;
      }
    },
    async getConsumerAndAccount() {
      let res = await getConsumerAndAccount(this.charId)
      this.consumerVo = res.data.consumerVo
      this.consumerAccount = res.data.consumerAccount
    },
    async getChargeAndDevice() {
      let res = await getChargeAndDevice(this.charId)
      this.billingModel = res.data
    },
    async getPowerData() {
      this.datetimes = []
      this.chartDatas = []
      this.chartDatas2 = []
      this.chartDatas3 = []
      await getOrderPower(this.powerParams).then(res => {
        res.data[0].chartDatas.forEach(item => {
          this.datetimes.push(this.parseTime(item.dateTime, '{m}-{d} {h}:{i}:{s}'))
          this.chartDatas.push(item.val)
        })
        res.data[1].chartDatas.forEach(item => {
          this.chartDatas2.push(item.val)
        })
        res.data[2].chartDatas.forEach(item => {
          this.chartDatas3.push(item.val)
        })
        this.lineChartData = {
          expectedData: this.chartDatas,
          actualData: [],
          dataV: this.chartDatas2,
          dataA: this.chartDatas3,
        }
        this.intervalNm = Math.floor(this.chartDatas.length / 15)
        this.powerUnit = [res.data[0].ymeasurement, res.data[1].ymeasurement, res.data[2].ymeasurement]
        /*if (this.chartDatas.length > 0) {
          let maxNum = JSON.parse(JSON.stringify(this.chartDatas))
          let maxNum2 = JSON.parse(JSON.stringify(this.chartDatas2))
          let maxNum3 = JSON.parse(JSON.stringify(this.chartDatas3))
          // console.log('Math.max',Math.max(...maxNum));
          this.powerMax = {
            maxW: String(Math.max(...maxNum) * 2),
            maxV: String(Math.max(...maxNum2) * 2),
            maxA: String(Math.max(...maxNum3) * 2),
          }
          this.powerMax = this.getNumInt(this.powerMax)
          console.log(this.getNumInt(this.powerMax))
        }*/
      })
    },
    getNumInt(val) {
      const num = val;
      const firstDigit = num.toString().charAt(0);
      const newNum = firstDigit + "0".repeat(num.toString().length - 1);
      return newNum
    },
    async getPowerSocData() {
      this.datetimes = []
      this.chartDatas = []
      this.chartDatas2 = []
      this.chartDatas3 = []
      await getOrderPowerSoc(this.powerParams).then(res => {
        res.data[0].chartDatas.forEach(item => {
          this.datetimes.push(this.parseTime(item.dateTime, '{m}-{d} {h}:{i}:{s}'))
          this.chartDatas.push(item.val)
        })
        res.data[1].chartDatas.forEach(item => {
          this.chartDatas2.push(item.val)
        })
        this.lineChartData = {
          expectedData: this.chartDatas,
          actualData: [],
          dataV: this.chartDatas2,
        }
        this.powerUnit = [res.data[0].ymeasurement, res.data[1].ymeasurement]
      })
    },
    async getPowerTemData() {
      this.datetimes = []
      await getOrderPowerTem(this.powerParams).then(res => {
        if (res.data[0].chartDatas.length > 0 && res.data[1].chartDatas.length > 0 && res.data[2].chartDatas.length > 0) {
          this.chartDatas = []
          this.chartDatas2 = []
          this.chartDatas3 = []
          res.data[0].chartDatas.forEach(item => {
            this.datetimes.push(this.parseTime(item.dateTime, '{m}-{d} {h}:{i}:{s}'))
            this.chartDatas.push(item.val)
          })
          res.data[1].chartDatas.forEach(item => {
            this.chartDatas2.push(item.val)
          })
          res.data[2].chartDatas.forEach(item => {
            this.chartDatas3.push(item.val)
          })
          this.lineChartData = {
            expectedData: this.chartDatas,
            actualData: [],
            dataV: this.chartDatas2,
            dataA: this.chartDatas3
          }
          this.powerUnit = [res.data[0].ymeasurement, res.data[1].ymeasurement, res.data[2].ymeasurement]
        } else {
          this.chartDatas = []
          res.data[3].chartDatas.forEach(item => {
            this.datetimes.push(this.parseTime(item.dateTime, '{m}-{d} {h}:{i}:{s}'))
            this.chartDatas.push(item.val)
          })
          this.lineChartData = {
            expectedData: this.chartDatas,
            actualData: [],
            dataV: [],
            dataA: []
          }
          this.powerUnit = [res.data[3].ymeasurement]
        }
      })
    },
    async changePowerType(e) {
      this.powerValue = e
      if (this.powerValue === '3') {
        // this.powerMax = '100'
        this.powerColor = 'red'
        this.powerType = '温度'
        await this.getPowerTemData()
        //this.$refs.lineChart.initChart()
      }
      if (this.powerValue === '2') {
        // this.powerMax = '100'
        this.powerColor = 'green'
        this.powerType = 'SOC'
        await this.getPowerSocData()
        //this.$refs.lineChart.initChart()
      }
      if (this.powerValue === '1') {
        //this.powerMax = '3000'
        this.powerColor = '#1890ff'
        this.powerType = '功率'
        await this.getPowerData()
        //this.$refs.lineChart.initChart()
      }
    },
    handleEnd(row, id) {
      this.$confirm('此操作将结束充电, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (row) {
          let res = closeOrder(row.id)
          row.status = 4
          row.statusType = '停止充电'
        }
        if (id) {
          let res = closeOrder(id)
          this.$modal.msgSuccess("操作成功");
          this.openDetail = false
        }
        this.$message({
          type: 'success',
          message: '关闭成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    async handleDetail(row) {
      this.powerParams.chargeOrderId = row.id
      this.openstatus = row.status
      this.charId = row.id
      this.consumerId = row.consumerId
      this.powerColor = '#1890ff'
      this.lineChartData = newVisitis
      getOrder(row.id).then(response => {
        this.orderDetail = response.data;
      });

      //this.getPowerData()
      this.openDetail = true

    },
    closeTimeChange(val) {
      if (!val) return
      this.queryParams.closeBeginTime = val[0]
      this.queryParams.closeEndTime = val[1]
    },
    timeChange(val) {
      console.log(val)
      if (!val) return
      this.queryParams.beginTime = val[0]
      this.queryParams.endTime = val[1]
    },
    handleChange(val) {
      //this.queryParams.beginChargeType = val[val.length-1]
      this.queryParams.unitType = val[val.length - 1]

    },
    async getChargeTypeList() {
      let res = await getChargeTypeList()
      this.chargeTypeList = res
      this.chargeTypeList.forEach(item => {
        item['desc'] = item['protocolName']
      })
    },
    /** 查询订单统计列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        beginChargeType: null,
        chargePort: null,
        consumerId: null,
        createTime: null,
        deviceId: null,
        planAmount: null,
        status: null,
        version: null,
        vin: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      //初始化时间
      /*this.queryParams.beginTime = null
      this.queryParams.endTime = null*/
      this.queryParams.closeBeginTime = null
      this.queryParams.closeEndTime = null
      this.deviceList = null
      this.resetForm("queryForm");
      this.one();
      this.getAllStation();
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单统计";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单统计";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除订单统计编号为"' + ids + '"的数据项？').then(function () {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      if (this.queryParams.timeExport || this.queryParams.closeTimeExport) {
        delete this.queryParams.timeExport
        delete this.queryParams.closeTimeExport
        this.exportStats = true
        this.download('business/order/export', {
          ...this.queryParams
        }, `order_${new Date().getTime()}.xlsx`).then(() => {
          setTimeout(() => {
            this.exportStats = false
          }, 5000)
        })
      } else {
        this.$modal.msgWarning("请选择充电开始时间或者充电结束时间");
        return
      }
    },
    handleOrderExport() {
      if (this.queryParams.timeExport || this.queryParams.closeTimeExport) {
        delete this.queryParams.timeExport
        delete this.queryParams.closeTimeExport
        this.exportStats = true
        this.download('business/order/exportReport', {
          ...this.queryParams
        }, `order_${new Date().getTime()}.xlsx`).then(() => {
          setTimeout(() => {
            this.exportStats = false
          }, 5000)
        })
      } else {
        this.$modal.msgWarning("请选择充电开始时间或者充电结束时间");
        return
      }
    },
    closeDetail() {
      this.activeName = 'first'
      this.powerValue = '1'
    }
  },


};
</script>
<style lang="scss" scoped>
.labelWidth {
  width: 150px;
}

/*.formFlex {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}*/

.el-tag--dark {
  border-color: #ffffff !important;
}
</style>
<style>
.el-table .success-row {
  background: #f0f9eb;
}

.closeBtn {
  text-align: right;
  padding-top: 30px;
}
</style>
